<template>
  <a-card :bordered="false" class="master-detail-container">
    <!-- 主列表区域 -->
    <div class="master-list">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="配方编码">
                <a-input placeholder="请输入配方编码" v-model="queryParam.formulaCode"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="配方号">
                <a-input placeholder="请输入配方号" v-model="queryParam.formulaNumber"></a-input>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus">
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="配方名称">
                  <a-input placeholder="请输入配方名称" v-model="queryParam.formulaDefine"></a-input>
                </a-form-item>
              </a-col>
            </template>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
        <!--<a-button type="primary" icon="download" @click="handleExportXls('pg配方清单')">导出</a-button>
        <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
          <a-button type="primary" icon="import">导入</a-button>
        </a-upload>-->
        <!-- 高级查询区域 -->
        <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
        </a-dropdown>-->
      </div>
      <!-- 查询区域-END -->

      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap1"
        :scroll="{x:true}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{type: 'radio', selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleCopy(record)">复制</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <!-- 子列表区域 -->
    <div class="detail-list" v-if="selectedRowKeys.length > 0">
      <a-card title="配方物料详情" :bordered="false">
        <a-spin :spinning="detailLoading">
          <a-table
            ref="detailTable"
            size="middle"
            bordered
            rowKey="id"
            :columns="detailColumns"
            :dataSource="detailData"
            :pagination="false"
            :loading="detailLoading"
            :footer="renderFooter">
            <!--<template slot="footer" v-if="detailData.length > 0">
              <tr>
                <td><strong>合计</strong></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td><strong>{{ totalProportion }}</strong></td>
                <td><strong>{{ totalActualNumber }}</strong></td>
                <td></td>
              </tr>
            </template>-->
          </a-table>
        </a-spin>
      </a-card>
    </div>

    <ips-pg-formula-list-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import IpsPgFormulaListModal from './modules/IpsPgFormulaListModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import '@/assets/less/TableExpand.less'
  import {getAction, deleteAction} from '@/api/manage'
  import Decimal from 'decimal.js'

  export default {
    name: "IpsPgFormulaListList",
    mixins:[JeecgListMixin],
    components: {
      IpsPgFormulaListModal
    },
    data () {
      return {
        description: 'P&G配方清单管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'配方年',
            align:"center",
            dataIndex: 'formulaYear'
          },
          {
            title:'配方编码',
            align:"center",
            dataIndex: 'formulaCode'
          },
          {
            title:'配方号',
            align:"center",
            dataIndex: 'formulaNumber'
          },
          {
            title:'配方名称',
            align:"center",
            dataIndex: 'formulaDefine'
          },
          {
            title:'配方类别',
            align:"center",
            dataIndex: 'formulaCategory_dictText'
          },
          {
            title:'配方类型',
            align:"center",
            dataIndex: 'formulaType_dictText'
          },
          {
            title:'类型',
            align:"center",
            dataIndex: 'formulaDesc_dictText'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        // 子表数据
        detailData: [],
        detailLoading: false,
        // 子表列定义
        detailColumns: [
          {
            title: '物料编码',
            dataIndex: 'materialCode',
            align: "center",
            width: 150
          },
          {
            title: '物料名称',
            dataIndex: 'materialName',
            align: "center",
            width: 150
          },
          {
            title: '规格型号',
            dataIndex: 'materialSpec',
            align: "center",
            width: 150
          },
          {
            title: '单位',
            dataIndex: 'materialUnit_dictText',
            align: "center",
            width: 100
          },
          {
            title: '是否自带料',
            dataIndex: 'isSelfProvided_dictText',
            align: "center",
            width: 120
          },
          {
            title: '配方%',
            dataIndex: 'formulaProportion',
            align: "center",
            width: 100
          },
          {
            title: '实际数量',
            dataIndex: 'actualNumber',
            align: "center",
            width: 120
          },
          {
            title: '配方公式',
            dataIndex: 'formulaExpression',
            align: "center",
            width: 300
          }
        ],
        url: {
          list: "/ipspgformulalist/ipsPgFormulaList/list",
          detailList: "/ipspgformulalist/ipsPgFormulaList/queryMaterialDetails",
          delete: "/ipspgformulalist/ipsPgFormulaList/delete",
          deleteBatch: "/ipspgformulalist/ipsPgFormulaList/deleteBatch",
          exportXlsUrl: "/ipspgformulalist/ipsPgFormulaList/exportXls",
          importExcelUrl: "ipspgformulalist/ipsPgFormulaList/importExcel",

        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
    },
    computed: {
      // 计算合计行数据
      totalProportion() {
        return this.detailData.reduce((sum, item) => {
          return sum + (parseFloat(item.formulaProportion) || 0);
        }, 0).toFixed(4);
      },
      totalActualNumber() {
        return this.detailData.reduce((sum, item) => {
          return sum + (parseFloat(item.actualNumber) || 0);
        }, 0).toFixed(4);
      },
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      handleCopy(record){
        console.log("rrr",record)
        this.$refs.modalForm.copy(record);
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
      },
      // 覆盖查询方法
      searchQuery() {
        JeecgListMixin.methods.searchQuery.call(this);
        this.selectedRowKeys = [];
        this.detailData = [];
      },
      // 覆盖重置方法
      searchReset() {
        JeecgListMixin.methods.searchReset.call(this);
        this.selectedRowKeys = [];
        this.detailData = [];
      },
      // 覆盖删除方法
      handleDelete(id) {
        const that = this;
        deleteAction(that.url.delete, { id: id }).then(res => {
          if (res.success) {
            that.$message.success(res.message);
            that.loadData(); // 重新加载主列表数据
            that.selectedRowKeys = []; // 清空选中行
            that.detailData = []; // 清空子数据
          } else {
            that.$message.warning(res.message);
          }
        }).catch(error => {
          this.$message.error("删除失败");
        });
      },
      // 行选择变化事件
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
        if (selectedRowKeys.length > 0) {
          this.loadDetailData(selectedRowKeys[0]);
        } else {
          this.detailData = [];
        }
      },
      // 加载子表数据
      loadDetailData(mainId) {
        this.detailLoading = true;
        this.detailData = [];

        getAction(this.url.detailList, { mainId: mainId }).then(res => {
          if (res.success) {
            this.detailData = res.result;
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.detailLoading = false;
        });
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'int',value:'formulaYear',text:'配方年',dictCode:''})
        fieldList.push({type:'string',value:'formulaCode',text:'配方编码',dictCode:''})
        fieldList.push({type:'string',value:'formulaNumber',text:'配方号',dictCode:''})
        fieldList.push({type:'string',value:'formulaDefine',text:'配方名称',dictCode:''})
        fieldList.push({type:'string',value:'formulaCategory',text:'配方类别',dictCode:'formula_category'})
        fieldList.push({type:'string',value:'formulaType',text:'配方类型',dictCode:'formula_type'})
        fieldList.push({type:'string',value:'formulaDesc',text:'类型',dictCode:'formula_desc'})
        this.superFieldList = fieldList
      },
      // 自定义 footer 内容
      renderFooter() {
        return (
          <div style="width: 100%; display: flex; gap: 8px; flex-wrap: nowrap; overflow-x: auto;">
            <div style="order: 1; flex: 0 1 auto; min-width: 13.65%; text-align: center; border-right: 1px solid #f0f0f0;">合计</div>
            <div style="order: 2; flex: 0 1 auto; min-width: 48%; text-align: right; border-right: 1px solid #f0f0f0;">{this.totalProportion}</div>
            <div style="order: 3; flex: 0 1 auto; min-width: 14.8%; text-align: center;">{this.totalActualNumber}</div>
          </div>
        );
      }
    }
  }
</script>
<style scoped>
  .master-detail-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .master-list {
    margin-bottom: 20px;
  }

  .detail-list {
    flex: 1;
    overflow: auto;
  }
  @import '~@assets/less/common.less';
</style>